#-*- coding:utf-8 -*- 
import sys
import os
import utils

IDMap = {};

logFileList = []

def listAllLogFile(logDir):
    if(os.path.isdir(logDir)):
        for f in os.listdir(logDir):
            sub = os.path.join(logDir, f);
            listAllLogFile(sub);
    elif os.path.isfile(logDir):
        logFileList.append(logDir);


def getShortID(s):
    s = '"%s"'%s;
    if IDMap.has_key(s):
        return IDMap[s].strip('"');

def _readIDMap(path):
    f = open(path, 'r');
    f.readline();
    for line in f:
        li = line.strip().split(',');
        if li[1]:
            IDMap[li[0]] = li[1];
    f.close();

def readIDMap(idDir):
    for li in os.listdir(idDir): 
        path = os.path.join(idDir, li) 
        if os.path.isdir(path):
            print "Wrong"
        else:
            _readIDMap(path); 


def filterLog(path, destFile):
    f = open(path, 'r');
    dest = open(destFile, 'w');
    for line in f:
        li = line.strip().split('|');
        #print len(li);
        #assert(len(li) == 12);
    
        if int(li[3]) in (6 ,11) and li[7]=='search':
            dest.write('%s\t%s\t%s\n' %(getShortID(li[0]), li[3], li[8]));
    f.close();
    dest.close();

def main():
    idDir = '/home/wangshuxin/app_search/appidtoappoid';
    readIDMap(idDir);
    destDir = '/home/wangshuxin/operlog/';
    listAllLogFile('/home/wangshuxin/app_search/log/hispace_oper_log');
    for logFile in logFileList:
        print logFile
        p,f = os.path.split(logFile);
        d = f.split('_',3)[-1][:-4];
        destFile = os.path.join(destDir, d);
        print destFile;
        filterLog(logFile, destFile);
    

if __name__ == '__main__':
    main()
